// 测试数据管理工具
import { microservicesConfig, testUtils } from './microservices-config.js'

export class TestDataManager {
  constructor() {
    this.apiBaseUrl = microservicesConfig.apiGateway
    this.testData = microservicesConfig.testData
    this.createdUsers = []
    this.createdCourses = []
    this.createdExercises = []
    this.createdClasses = []
  }

  // 用户管理
  async createTestUser(userData = {}) {
    const defaultUser = testUtils.generateTestUser('Student')
    const user = { ...defaultUser, ...userData }
    
    try {
      const response = await cy.request({
        method: 'POST',
        url: `${this.apiBaseUrl}/api/users/register`,
        body: user,
        failOnStatusCode: false
      })
      
      if ([200, 201].includes(response.status)) {
        this.createdUsers.push(user)
        cy.log(`测试用户创建成功: ${user.account}`)
        return { success: true, user, response: response.body }
      } else if (response.status === 409) {
        cy.log(`用户已存在: ${user.account}`)
        return { success: false, reason: 'USER_EXISTS', user }
      } else {
        cy.log(`用户创建失败: ${response.status}`)
        return { success: false, reason: 'CREATE_FAILED', user, status: response.status }
      }
    } catch (error) {
      cy.log(`用户创建异常: ${error.message}`)
      return { success: false, reason: 'EXCEPTION', user, error }
    }
  }

  async createMultipleTestUsers(count = 5) {
    const users = {
      teachers: [],
      students: [],
      admins: []
    }

    // 创建教师用户
    for (let i = 0; i < Math.ceil(count / 3); i++) {
      const result = await this.createTestUser({ role: 'Teacher' })
      if (result.success) {
        users.teachers.push(result.user)
      }
    }

    // 创建学生用户
    for (let i = 0; i < Math.ceil(count * 2 / 3); i++) {
      const result = await this.createTestUser({ role: 'Student' })
      if (result.success) {
        users.students.push(result.user)
      }
    }

    // 创建管理员用户
    if (count > 3) {
      const result = await this.createTestUser({ role: 'Admin' })
      if (result.success) {
        users.admins.push(result.user)
      }
    }

    return users
  }

  // 课程管理
  async createTestCourse(courseData = {}, teacherToken = null) {
    const defaultCourse = {
      courseId: `TEST_${testUtils.generateRandomString(8)}`,
      courseName: `测试课程_${testUtils.generateRandomString(4)}`,
      description: '这是一个端到端测试课程',
      teachingGoal: '掌握端到端测试方法',
      examinationMethod: '项目实践 + 理论考试',
      credits: 3
    }
    
    const course = { ...defaultCourse, ...courseData }
    
    try {
      const headers = {
        'Content-Type': 'application/json'
      }
      
      if (teacherToken) {
        headers['Authorization'] = `Bearer ${teacherToken}`
      }
      
      const response = await cy.request({
        method: 'POST',
        url: `${this.apiBaseUrl}/api/courses`,
        body: course,
        headers,
        failOnStatusCode: false
      })
      
      if ([200, 201].includes(response.status)) {
        this.createdCourses.push(course)
        cy.log(`测试课程创建成功: ${course.courseName}`)
        return { success: true, course, response: response.body }
      } else {
        cy.log(`课程创建失败: ${response.status}`)
        return { success: false, reason: 'CREATE_FAILED', course, status: response.status }
      }
    } catch (error) {
      cy.log(`课程创建异常: ${error.message}`)
      return { success: false, reason: 'EXCEPTION', course, error }
    }
  }

  // 练习管理
  async createTestExercise(exerciseData = {}, courseId = null, teacherToken = null) {
    const defaultExercise = {
      name: `测试练习_${testUtils.generateRandomString(4)}`,
      description: '这是一个端到端测试练习',
      totalScore: 100,
      duration: 60,
      startTime: testUtils.formatDateTime(new Date()),
      endTime: testUtils.getFutureDate(7),
      courseId: courseId || 1,
      questions: [
        {
          type: 'single_choice',
          content: '这是一个测试选择题？',
          options: ['选项A', '选项B', '选项C', '选项D'],
          answer: 'A',
          score: 25
        },
        {
          type: 'multiple_choice',
          content: '这是一个测试多选题？',
          options: ['选项1', '选项2', '选项3', '选项4'],
          answer: ['A', 'B'],
          score: 25
        },
        {
          type: 'text',
          content: '这是一个测试简答题？',
          answer: '这是标准答案',
          score: 50
        }
      ]
    }
    
    const exercise = { ...defaultExercise, ...exerciseData }
    
    try {
      const headers = {
        'Content-Type': 'application/json'
      }
      
      if (teacherToken) {
        headers['Authorization'] = `Bearer ${teacherToken}`
      }
      
      const response = await cy.request({
        method: 'POST',
        url: `${this.apiBaseUrl}/api/exercises`,
        body: exercise,
        headers,
        failOnStatusCode: false
      })
      
      if ([200, 201].includes(response.status)) {
        this.createdExercises.push(exercise)
        cy.log(`测试练习创建成功: ${exercise.name}`)
        return { success: true, exercise, response: response.body }
      } else {
        cy.log(`练习创建失败: ${response.status}`)
        return { success: false, reason: 'CREATE_FAILED', exercise, status: response.status }
      }
    } catch (error) {
      cy.log(`练习创建异常: ${error.message}`)
      return { success: false, reason: 'EXCEPTION', exercise, error }
    }
  }

  // 班级管理
  async createTestClass(classData = {}, courseId = null, teacherToken = null) {
    const defaultClass = {
      classId: `CLASS_${testUtils.generateRandomString(6)}`,
      className: `测试班级_${testUtils.generateRandomString(4)}`,
      description: '这是一个端到端测试班级',
      maxStudents: 50,
      courseId: courseId || 1
    }
    
    const classInfo = { ...defaultClass, ...classData }
    
    try {
      const headers = {
        'Content-Type': 'application/json'
      }
      
      if (teacherToken) {
        headers['Authorization'] = `Bearer ${teacherToken}`
      }
      
      const response = await cy.request({
        method: 'POST',
        url: `${this.apiBaseUrl}/api/classes`,
        body: classInfo,
        headers,
        failOnStatusCode: false
      })
      
      if ([200, 201].includes(response.status)) {
        this.createdClasses.push(classInfo)
        cy.log(`测试班级创建成功: ${classInfo.className}`)
        return { success: true, class: classInfo, response: response.body }
      } else {
        cy.log(`班级创建失败: ${response.status}`)
        return { success: false, reason: 'CREATE_FAILED', class: classInfo, status: response.status }
      }
    } catch (error) {
      cy.log(`班级创建异常: ${error.message}`)
      return { success: false, reason: 'EXCEPTION', class: classInfo, error }
    }
  }

  // 获取用户令牌
  async getUserToken(account, password) {
    try {
      const response = await cy.request({
        method: 'POST',
        url: `${this.apiBaseUrl}/api/users/login`,
        body: { account, password },
        failOnStatusCode: false
      })
      
      if (response.status === 200 && response.body.data && response.body.data.token) {
        return { success: true, token: response.body.data.token }
      } else {
        cy.log(`获取令牌失败: ${response.status}`)
        return { success: false, status: response.status }
      }
    } catch (error) {
      cy.log(`获取令牌异常: ${error.message}`)
      return { success: false, error }
    }
  }

  // 创建完整的测试场景
  async createTestScenario(scenarioName = 'default') {
    const scenario = {
      name: scenarioName,
      users: {},
      courses: [],
      exercises: [],
      classes: []
    }

    cy.log(`开始创建测试场景: ${scenarioName}`)

    try {
      // 创建测试用户
      const teacherResult = await this.createTestUser({ 
        role: 'Teacher',
        account: `teacher_${scenarioName}_${testUtils.generateRandomString(4)}`,
        name: `测试教师_${scenarioName}`
      })
      
      if (teacherResult.success) {
        scenario.users.teacher = teacherResult.user
      }

      const studentResult = await this.createTestUser({ 
        role: 'Student',
        account: `student_${scenarioName}_${testUtils.generateRandomString(4)}`,
        name: `测试学生_${scenarioName}`
      })
      
      if (studentResult.success) {
        scenario.users.student = studentResult.user
      }

      // 获取教师令牌
      let teacherToken = null
      if (scenario.users.teacher) {
        const tokenResult = await this.getUserToken(
          scenario.users.teacher.account, 
          scenario.users.teacher.password
        )
        if (tokenResult.success) {
          teacherToken = tokenResult.token
        }
      }

      // 创建测试课程
      if (teacherToken) {
        const courseResult = await this.createTestCourse({
          courseName: `${scenarioName}测试课程`,
          description: `${scenarioName}场景的测试课程`
        }, teacherToken)
        
        if (courseResult.success) {
          scenario.courses.push(courseResult.course)
          
          // 创建测试班级
          const classResult = await this.createTestClass({
            className: `${scenarioName}测试班级`
          }, courseResult.course.courseId, teacherToken)
          
          if (classResult.success) {
            scenario.classes.push(classResult.class)
          }

          // 创建测试练习
          const exerciseResult = await this.createTestExercise({
            name: `${scenarioName}测试练习`
          }, courseResult.course.courseId, teacherToken)
          
          if (exerciseResult.success) {
            scenario.exercises.push(exerciseResult.exercise)
          }
        }
      }

      cy.log(`测试场景创建完成: ${scenarioName}`)
      return { success: true, scenario }

    } catch (error) {
      cy.log(`测试场景创建失败: ${error.message}`)
      return { success: false, error, scenario }
    }
  }

  // 清理测试数据
  async cleanupTestData() {
    cy.log('开始清理测试数据...')
    
    // 注意：实际的清理操作需要根据后端API来实现
    // 这里只是记录需要清理的数据
    
    const cleanupSummary = {
      users: this.createdUsers.length,
      courses: this.createdCourses.length,
      exercises: this.createdExercises.length,
      classes: this.createdClasses.length
    }

    // 清理练习
    for (const exercise of this.createdExercises) {
      try {
        await cy.request({
          method: 'DELETE',
          url: `${this.apiBaseUrl}/api/exercises/${exercise.id}`,
          failOnStatusCode: false
        })
      } catch (error) {
        cy.log(`清理练习失败: ${exercise.name}`)
      }
    }

    // 清理班级
    for (const classInfo of this.createdClasses) {
      try {
        await cy.request({
          method: 'DELETE',
          url: `${this.apiBaseUrl}/api/classes/${classInfo.id}`,
          failOnStatusCode: false
        })
      } catch (error) {
        cy.log(`清理班级失败: ${classInfo.className}`)
      }
    }

    // 清理课程
    for (const course of this.createdCourses) {
      try {
        await cy.request({
          method: 'DELETE',
          url: `${this.apiBaseUrl}/api/courses/${course.id}`,
          failOnStatusCode: false
        })
      } catch (error) {
        cy.log(`清理课程失败: ${course.courseName}`)
      }
    }

    // 清理用户（通常不建议删除用户，可能影响数据完整性）
    // 这里只记录，不实际删除
    cy.log(`需要清理的用户数量: ${this.createdUsers.length}`)

    // 重置数组
    this.createdUsers = []
    this.createdCourses = []
    this.createdExercises = []
    this.createdClasses = []

    cy.log('测试数据清理完成', cleanupSummary)
    return cleanupSummary
  }

  // 验证测试数据
  async verifyTestData() {
    const verification = {
      users: { total: this.createdUsers.length, verified: 0 },
      courses: { total: this.createdCourses.length, verified: 0 },
      exercises: { total: this.createdExercises.length, verified: 0 },
      classes: { total: this.createdClasses.length, verified: 0 }
    }

    // 验证用户
    for (const user of this.createdUsers) {
      try {
        const response = await cy.request({
          method: 'POST',
          url: `${this.apiBaseUrl}/api/users/login`,
          body: { account: user.account, password: user.password },
          failOnStatusCode: false
        })
        
        if (response.status === 200) {
          verification.users.verified++
        }
      } catch (error) {
        cy.log(`用户验证失败: ${user.account}`)
      }
    }

    // 验证课程（需要适当的权限）
    // 这里简化处理，实际应该通过API验证

    cy.log('测试数据验证完成', verification)
    return verification
  }

  // 获取测试数据摘要
  getTestDataSummary() {
    return {
      users: this.createdUsers.map(u => ({ account: u.account, role: u.role })),
      courses: this.createdCourses.map(c => ({ courseId: c.courseId, name: c.courseName })),
      exercises: this.createdExercises.map(e => ({ name: e.name, courseId: e.courseId })),
      classes: this.createdClasses.map(c => ({ classId: c.classId, name: c.className })),
      totals: {
        users: this.createdUsers.length,
        courses: this.createdCourses.length,
        exercises: this.createdExercises.length,
        classes: this.createdClasses.length
      }
    }
  }
}

// 导出单例实例
export const testDataManager = new TestDataManager()

// Cypress命令扩展
Cypress.Commands.add('createTestScenario', (scenarioName) => {
  return testDataManager.createTestScenario(scenarioName)
})

Cypress.Commands.add('cleanupTestData', () => {
  return testDataManager.cleanupTestData()
})

Cypress.Commands.add('getTestDataSummary', () => {
  return testDataManager.getTestDataSummary()
})
